package cn.net.cfss.fgbp.provider.console.spi;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RestController;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import cn.hutool.crypto.digest.BCrypt;
import cn.net.cfss.fgbp.api.console.constant.DeleteFlagEnum;
import cn.net.cfss.fgbp.api.console.constant.UserStatusEnum;
import cn.net.cfss.fgbp.api.console.dto.SysUserBusiTypeDto;
import cn.net.cfss.fgbp.api.console.dto.SysUserDto;
import cn.net.cfss.fgbp.api.console.dto.SysUserRoleDto;
import cn.net.cfss.fgbp.api.console.inte.ISysUserService;
import cn.net.cfss.fgbp.api.console.vo.SysUserDetailVo;
import cn.net.cfss.fgbp.api.console.vo.SysUserLoginVo;
import cn.net.cfss.fgbp.api.console.vo.SysUserVo;
import cn.net.cfss.fgbp.base.page.PageData;
import cn.net.cfss.fgbp.base.service.FeignBaseService;
import cn.net.cfss.fgbp.provider.console.biz.SysUserBusiTypeDtoBiz;
import cn.net.cfss.fgbp.provider.console.biz.SysUserDtoBiz;
import cn.net.cfss.fgbp.provider.console.biz.SysUserRoleDtoBiz;
import cn.net.cfss.fgbp.provider.console.utils.FgbpIdUtil;
import lombok.extern.slf4j.Slf4j;

@RestController
@Slf4j
public class SysUserSpi extends FeignBaseService implements ISysUserService {

    @Autowired
    SysUserDtoBiz sysUserDtoBiz;

    @Autowired
    SysUserRoleDtoBiz sysUserRoleDtoBiz;

    @Autowired
    SysUserBusiTypeDtoBiz sysUserBusiTypeDtoBiz;


    @Override
    public Long countByUsername(String username) {
        SysUserVo search = new SysUserVo();
        search.setUsername(username);
        search.setDeleteFlag(DeleteFlagEnum.NOT_DEL);
        Long resp = sysUserDtoBiz.selectCount(search);
        return resp;
    }

    /**
     * 新增用户
     *
     * @param sysUserVo
     * @return
     */
    @Transactional
    @Override
    public SysUserDto addUserRole(SysUserVo sysUserVo) {
        sysUserVo.setId(sysUserDtoBiz.getUID());
        sysUserVo.setCreateTime(new Date());
        sysUserVo.setDeleteFlag(DeleteFlagEnum.NOT_DEL);
        sysUserVo.setSalt(BCrypt.gensalt());
        sysUserVo.setPassword(BCrypt.hashpw(sysUserVo.getPlainPassword(), sysUserVo.getSalt()));
        SysUserDto user = sysUserDtoBiz.selectById(getUserId());
//        if(null != user.getServiceProvider()){
//        	sysUserVo.setServiceProvider(user.getServiceProvider());
//        	sysUserVo.setServiceProviderName(user.getServiceProviderName());
//    	}
        sysUserDtoBiz.insert(sysUserVo);
        List<Long> roleIds = sysUserVo.getRoleIds();
        if (roleIds != null && roleIds.size() > 0) {
            List<SysUserRoleDto> userRoleDtoList = new ArrayList<>();
            for (Long roleId : roleIds) {
                userRoleDtoList.add(new SysUserRoleDto(FgbpIdUtil.generateId(), sysUserVo.getId(), roleId));
            }
            sysUserRoleDtoBiz.insertBatch(userRoleDtoList);
        }
        List<Long> busTypeIds = sysUserVo.getBusiTypeIds();
        if (busTypeIds != null && busTypeIds.size() > 0) {
            List<SysUserBusiTypeDto> sysUserBusiTypeDtoList = new ArrayList<>();
            for (Long busiTypeId : busTypeIds) {
                sysUserBusiTypeDtoList.add(new SysUserBusiTypeDto(FgbpIdUtil.generateId(), sysUserVo.getId(), busiTypeId));
            }
            sysUserBusiTypeDtoBiz.insertBatch(sysUserBusiTypeDtoList);
        }
        return sysUserVo;
    }

    /**
     * 修改用户
     *
     * @param sysUserVo
     * @return
     */
    @Transactional
    @Override
    public SysUserDto editUserRole(SysUserVo sysUserVo) {
        SysUserVo req = sysUserVo;
        sysUserVo.setUpdateTime(new Date());
        if (!StringUtils.isAnyBlank(sysUserVo.getPlainPassword(), sysUserVo.getConfirmPassword())
                && sysUserVo.getPlainPassword().equals(sysUserVo.getConfirmPassword())) {
            sysUserVo.setSalt(BCrypt.gensalt());
            sysUserVo.setPassword(BCrypt.hashpw(sysUserVo.getPlainPassword(), sysUserVo.getSalt()));
        } else {
            //sysUserVo.setSalt(BCrypt.gensalt());
            //sysUserVo.setPassword(BCrypt.hashpw(sysUserVo.getPlainPassword(), sysUserVo.getSalt()));
            sysUserVo.setPassword(null);
        }
        sysUserDtoBiz.updateSelectiveById(sysUserVo);
        setRole(sysUserVo);
        setBusiType(sysUserVo);

        return sysUserVo;
    }

    /**
     * 锁定用户
     *
     * @param userId
     * @return
     */
    @Override
    public void lockUser(Long userId) {
        SysUserDto sysUserDto = new SysUserDto(userId);
        sysUserDto.setUserStatus(UserStatusEnum.LOCKED);
        sysUserDto.setUpdateTime(new Date());
        sysUserDtoBiz.updateSelectiveById(sysUserDto);

    }

    /**
     * 解锁用户
     *
     * @param userId
     * @return
     */
    @Override
    public void unlockUser(Long userId) {

        SysUserDto sysUserDto = new SysUserDto(userId);
        sysUserDto.setUserStatus(UserStatusEnum.NORMAL);
        sysUserDto.setUpdateTime(new Date());
        sysUserDtoBiz.updateSelectiveById(sysUserDto);
    }

    /**
     * 修改用户密码
     *
     * @param sysUserVo
     * @return
     */
    @Override
    public void updatePwd(SysUserVo sysUserVo) {
        if (StringUtils.isNoneBlank(sysUserVo.getOriginalPassword(), sysUserVo.getPlainPassword())
                && sysUserVo.getOriginalPassword().equals(sysUserVo.getPlainPassword())) {
            sysUserVo.setSalt(BCrypt.gensalt());
            sysUserVo.setPassword(BCrypt.hashpw(sysUserVo.getPlainPassword(), sysUserVo.getSalt()));
            sysUserVo.setUpdateTime(new Date());
            sysUserDtoBiz.updateSelectiveById(sysUserVo);
            log.info("请求参数:{}，返回参数：{}", sysUserVo, null);
        } else {
            log.error("原密码或者明文密码为空!");

        }
    }

    /**
     * 设置用户角色
     *
     * @param sysUserVo
     * @return
     */
    @Override
    public void setRole(SysUserVo sysUserVo) {
        List<Long> roleIds = sysUserVo.getRoleIds();
        if (roleIds != null && roleIds.size() > 0) {
            sysUserRoleDtoBiz.deleteByUserId(sysUserVo.getId());
            List<SysUserRoleDto> sysUserRoleDtoList = new ArrayList<>();
            for (Long roleId : roleIds) {
                sysUserRoleDtoList.add(new SysUserRoleDto(FgbpIdUtil.generateId(), sysUserVo.getId(), roleId));
            }
            sysUserRoleDtoBiz.insertBatch(sysUserRoleDtoList);

            log.info("请求参数:{}，返回参数：{}", sysUserVo, null);
        } else {
            log.error("入参的所属角色ID集合为空!");
        }
    }

    /**
     * 设置用户业务类型
     *
     * @param sysUserVo
     * @return
     */
    @Override
    public void setBusiType(SysUserVo sysUserVo) {
        List<Long> busiTypeIds = sysUserVo.getBusiTypeIds();
        if (busiTypeIds != null && busiTypeIds.size() > 0) {
            sysUserBusiTypeDtoBiz.deleteByUserId(sysUserVo.getId());
            List<SysUserBusiTypeDto> sysUserBusiTypeDtoList = new ArrayList<>();
            for (Long busiTypeId : busiTypeIds) {
                sysUserBusiTypeDtoList.add(new SysUserBusiTypeDto(FgbpIdUtil.generateId(), sysUserVo.getId(), busiTypeId));
            }
            sysUserBusiTypeDtoBiz.insertBatch(sysUserBusiTypeDtoList);

        } else {
            log.error("入参的所属业务类型ID集合为空!");
        }
    }

    /**
     * 根据ID删除用户
     *
     * @param userId
     * @return
     */
    @Override
    public void delete(Long userId) {

        SysUserVo sysUserVo = new SysUserVo();
        sysUserVo.setId(userId);
        sysUserVo.setDeleteFlag(DeleteFlagEnum.DEL);
        sysUserDtoBiz.updateSelectiveById(sysUserVo);
        sysUserRoleDtoBiz.deleteByUserId(userId);
        sysUserBusiTypeDtoBiz.deleteByUserId(userId);
        log.info("请求参数:{}，返回参数：{}", userId, null);
    }

    /**
     * 根据ID数组批量删除用户
     *
     * @param userIds
     * @return
     */
    @Override
    public int deleteBatchByLogic(List<Long> userIds) {

        sysUserRoleDtoBiz.deleteBatchByUserId(userIds);
        sysUserBusiTypeDtoBiz.deleteBatchByUserId(userIds);
        int resp = sysUserDtoBiz.deleteBatchByLogic(userIds);

        return resp;
    }

    /**
     * 根据ID查询用户数据
     *
     * @param userId
     * @return
     */
    @Override
    public SysUserVo get(Long userId) {
        SysUserVo sysUserVo = sysUserDtoBiz.getByUserId(userId);
        if (sysUserVo != null) {
            sysUserVo.setRoleList(sysUserRoleDtoBiz.getRoleListByUserId(userId));
            sysUserVo.setBusiTypeList(sysUserBusiTypeDtoBiz.getBusiTypeListByUserId(userId));
        }

        return sysUserVo;
    }

    /**
     * 根据ID查询用户数据
     *
     * @param username
     * @return
     */
    @Override
    public SysUserDto queryByUsername(String username) {
        SysUserVo search = new SysUserVo();
        search.setUsername(username);
        search.setDeleteFlag(DeleteFlagEnum.NOT_DEL);
        SysUserDto dto = sysUserDtoBiz.selectOne(search);
        return dto;
    }

    /**
     * 根据条件查询用户列表
     *
     * @param sysUserVo
     * @return
     */
    @Override
    public List<SysUserDto> queryList(SysUserVo sysUserVo) {

        sysUserVo.setDeleteFlag(DeleteFlagEnum.NOT_DEL);
        List<SysUserDto> dtoList = sysUserDtoBiz.selectList(sysUserVo);

        return dtoList;
    }

    /**
     * 分页查询用户列表数据
     *
     * @param page
     * @return
     */
    @Override
    public PageData<SysUserVo> queryByPage(PageData<SysUserVo> page) {
        PageData<SysUserVo> req = page;

        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        SysUserVo search = page.getSearch();

        search.setDeleteFlag(DeleteFlagEnum.NOT_DEL);
        List<SysUserVo> list = sysUserDtoBiz.queryList(search);
        Page<SysUserVo> pageInfo = (Page<SysUserVo>) list;
        page.setRows(list);
        page.setTotal(pageInfo.getTotal());

        return page;
    }

    /**
     * 校验用户的唯一性
     *
     * @param username
     * @return
     */
    @Override
    public boolean uniquenessCheck(String username, Long id) {

        try {
            boolean flag = sysUserDtoBiz.check(username, id);
            return flag;
        } catch (Exception e) {
            log.error("用户唯一校验错误:{}", e.getMessage());
            //有异常情况调用这个方保存日志
            return false;
        }
    }

    /**
     * 用户登录，登录成功返回角色id集合
     *
     * @param username
     * @param password
     * @return
     */
    @Override
    public SysUserLoginVo login(String username, String password, String ip) {
        

        SysUserLoginVo vo = sysUserDtoBiz.login(username, password, ip);
        return vo;
    }

    @Override
    public SysUserDetailVo getPermissions(String userId) {
        if (StringUtils.isBlank(userId)) {
            return null;
        }
        return sysUserDtoBiz.getPermissions(userId);
    }

    @Override
    public List<SysUserDto> uniqueUser(SysUserVo sysUserVo) {
        return sysUserDtoBiz.uniqueUser(sysUserVo);
    }

    @Override
    public List<SysUserRoleDto> queryUserRole(SysUserRoleDto userRoleDto) {
        return sysUserRoleDtoBiz.selectList(userRoleDto);
    }

    @Override
    public Boolean checkUserRole(String roleCode, Long userId) {
        return sysUserDtoBiz.checkUserRole(roleCode, userId);
    }

    @Override
    public int test() {
        try {
            Thread.sleep(120);
        } catch (InterruptedException e) {
            log.error(e.getMessage());
            return -1;
        }
        return 0;
    }

    @Override
    public List<String> getRoleCodeByUid(Long userId) {
        return sysUserRoleDtoBiz.getRoleCodeByUid(userId);
    }

}
